"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const utils = require("utils");
const index = require("../../../utils/jwt/index.js");
const index$1 = require("../../../const/index.js");
const db = uniCloud.database();
const dbCmd = db.command;
const collection = db.collection("baby-users-aliyun");
async function searchUser(aliId) {
  const aggregate = collection.aggregate();
  const $ = dbCmd.aggregate;
  try {
    let matchRes = await aggregate.project({
      _id: 0,
      name: 1,
      id: 1,
      user_id: 1
    }).match({
      id: dbCmd.eq(aliId)
    }).limit(1).lookup({
      from: "baby-users",
      let: {
        user_id: "$user_id"
      },
      pipeline: $.pipeline().match(dbCmd.expr($.eq(["$_id", "$$user_id"]))).done(),
      as: "userList"
    }).end();
    let { data } = matchRes || {};
    let dataArr = Array.isArray(data) ? data : [];
    let first = dataArr[0];
    return [void 0, first];
  } catch (err) {
    return [new utils.InsideErr(err), void 0];
  }
}
async function createUser(tokenInfo, userInfo) {
  const transaction = await db.startTransaction();
  try {
    let now = Date.now();
    let addUser = await transaction.collection("baby-users").add({
      createDate: now
    });
    let aliUser = await transaction.collection("baby-users-aliyun").add({
      id: userInfo.id,
      createDate: now,
      name: userInfo.name || "",
      avatar: userInfo.avatar || "",
      phone: userInfo.phone || "",
      user_id: addUser.id
    });
    await transaction.commit();
    let resultTokenInfo = {
      name: userInfo.name,
      app: {
        access_token: index.jwt.sign(
          { id: addUser.id, ali: aliUser.id },
          index$1.AppToken.secret,
          60 * 60 * 2
        ),
        refresh_token: index.jwt.sign(
          { id: addUser.id, ali: aliUser.id },
          index$1.AppToken.secret,
          60 * 60 * 24 * 3
        ),
        expires_in: 60 * 60 * 2 - 60 * 10
      },
      ali: {
        access_token: tokenInfo.access_token,
        refresh_token: tokenInfo.refresh_token,
        expires_in: tokenInfo.expires_in
      }
    };
    return [void 0, resultTokenInfo];
  } catch (error) {
    await transaction.rollback();
    return [new utils.InsideErr(error), void 0];
  }
}
function updateUserInfo(localData, tokenInfo, userInfo) {
  let appUserId = localData.user_id;
  let aliId = localData.id;
  let resultTokenInfo = {
    name: userInfo.name,
    app: {
      access_token: index.jwt.sign({ id: appUserId, ali: aliId }, index$1.AppToken.secret, 60 * 60 * 2),
      refresh_token: index.jwt.sign(
        { id: appUserId, ali: aliId },
        index$1.AppToken.secret,
        60 * 60 * 24 * 3
      ),
      expires_in: 60 * 60 * 2 - 60 * 10
    },
    ali: {
      access_token: tokenInfo.access_token,
      refresh_token: tokenInfo.refresh_token,
      expires_in: tokenInfo.expires_in
    }
  };
  return resultTokenInfo;
}
async function dbHandle(tokenInfo, userInfo) {
  let [localErr, localData] = await searchUser(userInfo.id);
  if (!utils.util.nilValue(localErr)) {
    return [localErr, void 0];
  }
  if (utils.util.nilValue(localData)) {
    return await createUser(tokenInfo, userInfo);
  } else {
    let info = updateUserInfo(localData, tokenInfo, userInfo);
    return [void 0, info];
  }
}
exports.dbHandle = dbHandle;
